import { useEffect, useMemo, useState } from 'react';
import { Button, Space, Form, Row, Col, Table, Select, DatePicker, Popover, Spin, Input, Card } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import type { QueryStubReportListParams, StubReport } from './services';
import { queryStubReportList, StubReportTimeType, queryStubReportStatistic } from './services'
import { enum2options } from '@/utils/enum2options';
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import StationSelect from '@/components/StationSelect';
import Ellipsis from '@/components/Ellipsis';
import dayjs from 'dayjs';
import { history, styled } from '@umijs/max'
import { EquipmentType } from '@/pages/station/stubList/services';
import { jump2target } from '@/utils/common';

const StatisticCard = styled.div`
  width: 100%;
  height: 110px;
  background: #F7F8FA;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0 40px;

  .content {
    width: 100%;

    .title {
      font-family: Microsoft YaHei, Microsoft YaHei;
      font-weight: 400;
      font-size: 14px;
      color: #222222;
    }

    .value {
      font-family: Microsoft YaHei, Microsoft YaHei;
      font-weight: bold;
      font-size: 20px;
      color: #222222;
      margin-top: 12px;
    }
  }
`

const StubReportPage: React.FC = () => {
  const [searchForm] = Form.useForm()
  const [searchParams, setSearchParams] = useState<QueryStubReportListParams>({
    pageNum: 1, pageSize: 10, timeType: StubReportTimeType.按天,
    beginDay: dayjs().subtract(31, 'days').format('YYYYMMDD'),
    endDay: dayjs().subtract(1, 'days').format('YYYYMMDD'),
  })
  const list = useRequest(() => queryStubReportList(searchParams), {
    refreshDeps: [searchParams],
  })
  const statistic = useRequest(() => queryStubReportStatistic(searchParams), {
    refreshDeps: [searchParams],
  })
  const timeType = Form.useWatch('timeType', searchForm)

  const onFinish = (formValues: any) => {
    const _format = formValues.timeType === StubReportTimeType.按天 ? 'YYYYMMDD' : 'YYYYMM'
    setSearchParams({
      ...searchParams,
      stationId: formValues.station ? formValues.station[0]?.id : undefined,
      stationName: formValues.station ? formValues.station[0]?.name : undefined,
      timeType: formValues.timeType,
      stubId: formValues.stubId,
      beginDay: formValues.timeRange[0]?.format(_format),
      endDay: formValues.timeRange[1]?.format(_format),
      pageNum: 1,
    })
  }

  const jump2chargeOrderListPage = (record: StubReport) => {
    let beginTime = '', endTime = ''
    if (searchParams.timeType === StubReportTimeType.按天) {
      beginTime = dayjs(searchParams.beginDay).format('YYYY-MM-DD 00:00:00')
      endTime = dayjs(searchParams.endDay).format('YYYY-MM-DD 23:59:59')
    } else {
      beginTime = dayjs(searchParams.beginDay).startOf('month').format('YYYY-MM-DD 00:00:00')
      const _endDay = dayjs(searchParams.endDay).endOf('month')
      const _today = dayjs()
      if (_endDay.isAfter(_today, 'day')) {
        endTime = _today.format('YYYY-MM-DD 23:59:59')
      } else {
        endTime = _endDay.format('YYYY-MM-DD 23:59:59')
      }
    }
    sessionStorage.setItem('_searchParams_stubReport', JSON.stringify({
      stationId: record.stationId,
      stationName: record.stationName,
      beginTime,  endTime,
      equipmentId: record.equipmentId,
    }))
    jump2target(`/order/chargeOrder?sKey=_searchParams_stubReport___${new Date().getTime()}`, {needRefresh: true})
  }

  const columns: ColumnsType<StubReport> = [
    {
      title: '设备编号',
      dataIndex: 'equipmentId',
      width: 100,
    },
    {
      title: '场站名称',
      dataIndex: 'stationName',
      width: 180,
      render: val => <Popover content={val}><Ellipsis>{val}</Ellipsis></Popover>
    },
    {
      title: '类型',
      dataIndex: 'stubType',
      width: 160,
      render: val => val ? EquipmentType[val] : '--'
    },
    {
      title: '充电次数',
      dataIndex: 'orderNum',
      width: 100,
      render: val => val?.toLocaleString()
    },
    {
      title: '充电总量(度)',
      dataIndex: 'power',
      width: 120,
      render: val => val?.toLocaleString()
    },
    {
      title: '充电时长(分钟)',
      dataIndex: 'chargeTime',
      width: 160,
      render: val => val?.toLocaleString()
    },
    {
      title: '消费总额(元)',
      dataIndex: 'totalMoney',
      width: 140,
      render: (_, record) => {
        const _total = parseFloat((record.electricMoney + record.serviceMoney).toFixed(2))
        return _total.toLocaleString()
      }
    },
    {
      title: '电费总额(元)',
      dataIndex: 'electricMoney',
      width: 140,
      render: val => val?.toLocaleString()
    },
    {
      title: '服务费总额(元)',
      dataIndex: 'serviceMoney',
      width: 160,
      render: val => val?.toLocaleString()
    },
    {
      title: '操作',
      key: 'operation',
      width: 80,
      fixed: 'right',
      render: (id: string, record) => {
        return <Space>
          <a onClick={() => jump2chargeOrderListPage(record)}>查看订单</a>
        </Space>
      }
    }
  ]

  const totalMoney = useMemo(() => {
    if (statistic.data) {
      const _data = statistic.data.data
      return parseFloat((_data.electricMoney + _data.serviceMoney).toFixed(2)).toLocaleString()
    }
    return '0.00'
  }, [statistic.data])

  const onValuesChange = (changed: any) => {
    if (changed.timeType === StubReportTimeType.按月) {
      searchForm.setFieldsValue({
        timeRange: [
          dayjs().subtract(1, 'month'),
          dayjs().subtract(1, 'month'),
        ]
      })
    } else if (changed.timeType === StubReportTimeType.按天) {
      searchForm.setFieldsValue({
        timeRange: [
          dayjs().subtract(31, 'days'),
          dayjs().subtract(1, 'days'),
        ]
      })
    }
  }

  useEffect(() => {
    const refresh = () => {
      list.refresh()
    }
    window.addEventListener('refreshStubReportList', refresh)
    return () => {
      window.removeEventListener('refreshStubReportList', refresh)
    }
  }, [])

  return (
    <div className='container'>
      <Card>
        <div className="form-area">
          <Form 
            name='searchStubReportForm' 
            form={searchForm} 
            onFinish={onFinish} 
            onValuesChange={onValuesChange}
            initialValues={{
              timeType: StubReportTimeType.按天,
              timeRange: [dayjs().subtract(31, 'days'), dayjs().subtract(1, 'days')]
            }}
          >
            <Row gutter={[20, 20]}>
              <Col span={7}>
                <Form.Item label='统计时间'>
                  <div style={{display: 'flex', gap: 8}}>
                    <Form.Item name='timeType' noStyle>
                      <Select options={enum2options(StubReportTimeType)} style={{width: 70}} allowClear={false} />
                    </Form.Item>
                    <div style={{flex: 1}}>
                      {
                        timeType === StubReportTimeType.按月 ? <Form.Item name='timeRange' noStyle>
                          <DatePicker.RangePicker picker='month' allowClear={false} style={{width: '100%'}} disabledDate={current => !current.isBefore(dayjs(), 'month')} />
                        </Form.Item> : <Form.Item name='timeRange' noStyle>
                          <DatePicker.RangePicker allowClear={false} style={{width: '100%'}} disabledDate={current => !current.isBefore(dayjs(), 'day')} />
                        </Form.Item>
                      }
                    </div>
                  </div>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='场站ID' name='station'>
                  <StationSelect allowClear />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='设备编号' name='stubId'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={5}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
        <Spin spinning={statistic.loading}>
          <Row gutter={24}>
            <Col span={4}>
              <StatisticCard>
                <div className="content">
                  <div className="title">充电次数</div>
                  <div className="value">{statistic.data?.data.orderNum?.toLocaleString()}</div>
                </div>
              </StatisticCard>
            </Col>
            <Col span={4}>
              <StatisticCard>
                <div className="content">
                  <div className="title">充电总量（度）</div>
                  <div className="value">{statistic.data?.data.power?.toLocaleString()}</div>
                </div>
              </StatisticCard>
            </Col>
            <Col span={4}>
              <StatisticCard>
                <div className="content">
                  <div className="title">充电时长（分钟）</div>
                  <div className="value">{statistic.data?.data.chargeTime?.toLocaleString()}</div>
                </div>
              </StatisticCard>
            </Col>
            <Col span={4}>
              <StatisticCard>
                <div className="content">
                  <div className="title">消费总额（元）</div>
                  <div className="value">{totalMoney}</div>
                </div>
              </StatisticCard>
            </Col>
            <Col span={4}>
              <StatisticCard>
                <div className="content">
                  <div className="title">电费总额（元）</div>
                  <div className="value">{statistic.data?.data.electricMoney?.toLocaleString()}</div>
                </div>
              </StatisticCard>
            </Col>
            <Col span={4}>
              <StatisticCard>
                <div className="content">
                  <div className="title">服务费总额（元）</div>
                  <div className="value">{statistic.data?.data.serviceMoney?.toLocaleString()}</div>
                </div>
              </StatisticCard>
            </Col>
          </Row>
        </Spin>
      </Card>
      <Card title='电桩报表'>
        <Table<StubReport>
          rowKey='equipmentId'
          loading={list.loading}
          dataSource={list.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: list.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </Card>
    </div>
  );
};

export default StubReportPage;
